// $codepro.audit.disable
package edu.gatech.oad.cyberdoc.view;

import java.awt.FlowLayout;
import java.awt.SystemColor;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Arrays;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import edu.gatech.oad.cyberdoc.presenter.Presenter;
import edu.gatech.oad.cyberdoc.view.report.WeightChartDialog;

@SuppressWarnings("serial")
public class ViewUserPanel extends ApplicationPanel {

	/**
	 * The logger for this class.
	 */
	private static final Logger LOG;

	static {
		LOG = Logger.getLogger("edu.gatech.oad.cyberdoc.view."
				+ "ViewUserPanel");
	}
	
	private JTable table_3;
	private JList users;
	private JTextField nameField;
	private JTextField typeField;
	private JTextField passwordField;
	private JTextField confirmField;
	private JLabel lblStatus;
	
	private int[] weights;

	/**
	 * Create the panel.
	 */
	public ViewUserPanel() {
		setBackground(SystemColor.inactiveCaptionBorder);
		setLayout(null);

		JPanel top = new JPanel();
		top.setBounds(0, 0, 584, 39);
		top.setBackground(SystemColor.inactiveCaptionBorder);
		add(top);
		top.setLayout(null);

		JPanel instructions = new JPanel();
		instructions.setBackground(SystemColor.inactiveCaptionBorder);
		FlowLayout fl_instructions = (FlowLayout) instructions.getLayout();
		fl_instructions.setAlignment(FlowLayout.LEFT);
		instructions.setBounds(10, 11, 306, 24);
		top.add(instructions);

		JLabel lblPleaseSelectA = new JLabel(
				"Please select what type of information you would like to view.");
		instructions.add(lblPleaseSelectA);

		JComboBox comboBox = new JComboBox();
		comboBox.setBounds(326, 11, 248, 20);
		top.add(comboBox);

		JPanel patientInfoCards = new JPanel();
		patientInfoCards.setBounds(10, 38, 281, 165);
		add(patientInfoCards);
		patientInfoCards.setLayout(null);

		JPanel TreatmentRecords = new JPanel();
		TreatmentRecords.setBounds(0, 0, 275, 165);
		patientInfoCards.add(TreatmentRecords);
		TreatmentRecords.setLayout(null);

		JLabel lblName = new JLabel("Name:");
		lblName.setBounds(303, 51, 40, 14);
		add(lblName);

		table_3 = new JTable();
		table_3.setBounds(0, 0, 275, 165);
		TreatmentRecords.add(table_3);

		users = new JList();
		users.addListSelectionListener(new ListSelectionListener() {
			public void valueChanged(ListSelectionEvent arg0) {
				int index = users.getSelectedIndex();

				if (index != -1) {
					String username = users.getModel().getElementAt(index)
							.toString();
					Presenter.getInstance().readUser(username);
				}
			}
		});
		users.setBounds(10, 235, 281, 155);
		add(users);

		JLabel lblPleaseSelectWhat = new JLabel(
				"Select the user you would like view:");
		lblPleaseSelectWhat.setBounds(10, 213, 307, 14);
		add(lblPleaseSelectWhat);

		JLabel lblType = new JLabel("Type:");
		lblType.setBounds(303, 85, 40, 14);
		add(lblType);

		nameField = new JTextField();
		nameField.setEditable(false);
		nameField.setBounds(409, 38, 134, 28);
		add(nameField);
		nameField.setColumns(10);

		typeField = new JTextField();
		typeField.setEditable(false);
		typeField.setBounds(409, 78, 134, 28);
		add(typeField);
		typeField.setColumns(10);

		JLabel lblNewPassword = new JLabel("New Password:");
		lblNewPassword.setBounds(303, 141, 94, 16);
		add(lblNewPassword);

		passwordField = new JPasswordField();
		passwordField.setBounds(409, 135, 134, 28);
		add(passwordField);
		passwordField.setColumns(10);

		confirmField = new JPasswordField();
		confirmField.setBounds(409, 175, 134, 28);
		add(confirmField);
		confirmField.setColumns(10);

		JLabel lblConfirm = new JLabel("Confirm:");
		lblConfirm.setBounds(303, 181, 61, 16);
		add(lblConfirm);

		JButton btnSave = new JButton("Save");
		btnSave.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				String password = passwordField.getText();
				String confirm = confirmField.getText();

				if (password.length() == 0) {
					JOptionPane.showMessageDialog(null,
							"The password field cannot be left blank.",
							"Invalid Password", JOptionPane.ERROR_MESSAGE);
				} else if (!password.equals(confirm)) {
					JOptionPane.showMessageDialog(null,
							"The passwords do not match.", "Invalid Password",
							JOptionPane.ERROR_MESSAGE);
				} else {
					Presenter.getInstance().updateUser(nameField.getText(),
							passwordField.getText());
				}
			}
		});
		btnSave.setBounds(303, 213, 117, 29);
		add(btnSave);
		
		lblStatus = new JLabel("");
		lblStatus.setBounds(303, 251, 240, 16);
		add(lblStatus);
		
		JButton btnDelete = new JButton("Delete");
		btnDelete.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				Presenter.getInstance().deleteUser(nameField.getText());
			}
		});
		btnDelete.setBounds(174, 391, 117, 29);
		add(btnDelete);
		
		JButton btnCreate = new JButton("Create");
		btnCreate.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				new CreateUserDialog();
			}
		});
		btnCreate.setBounds(6, 391, 117, 29);
		add(btnCreate);
		
		JButton btnWeightChart = new JButton("Weight Chart");
		btnWeightChart.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				if (weights != null) {
					new WeightChartDialog(weights);
				}
			}
		});
		btnWeightChart.setBounds(419, 213, 117, 29);
		add(btnWeightChart);

	}

	@Override
	public void show(JSONObject response) {
		try {
			String action = response.getString("action");

			if (action.equals("view_users")) {
				LOG.info("Showing list of users");

				JSONArray array = response.getJSONArray("users");
				Object[] data = new Object[array.length()];

				for (int i = 0; i < array.length(); i++) {
					JSONObject element = new JSONObject(array.get(i).toString());
					data[i] = element.getString("username");
				}

				LOG.info("Showing " + data.length + " users: "
						+ Arrays.toString(data));

				users.setListData(data);
				
				nameField.setText("");
				typeField.setText("");
				passwordField.setText("");
				confirmField.setText("");
				lblStatus.setText("");
				weights = null;
			} else if (action.equals("read_user")) {
				JSONObject user = response.getJSONObject("user");
				LOG.info("Showing user " + user.getString("username"));

				nameField.setText(user.getString("username"));
				typeField.setText(user.getString("type"));
				
				if (user.has("weights")) {
					JSONArray weights = user.getJSONArray("weights");
					this.weights = new int[weights.length()];
					
					for (int i = 0; i < this.weights.length; i++) {
						this.weights[i] = weights.getInt(i);
					}
				}
			} else if(action.equals("update_user")) {
				LOG.info("User updated");
				
				lblStatus.setText(nameField.getText() + "'s account updated.");
			} else {
				LOG.warning("Panel shown for unexpected action");
			}
		} catch (JSONException e) {
			LOG.log(Level.SEVERE, "Expected key does not exist in response", e);
		}
	}
}
